/**
 * @class   PlayerGStreamer010
 * @brief   Low-level Bindings to GStreamer library. Multiple instance are
 *          supported, dafault sound system is ALSA.
 *
 *          See file asoundrc-sample for advanced ALSA configuration, the
 *          example will enable multiple indipendent channels using a cheap
 *          integrated (dolby) soundcard. Moreover it will also create some
 *          virtual devices.
 *
 *          Implemented on Linux for GStreamer 0.10 or later.
 *          Tested with GStreamer 0.10.19 (on Debian Lenny).
 *
 *
 * @see     PlayerGStreamer
 ****************************************************************************
 * @version 0.8.384 $Id: PlayerGStreamer010.h 2824 2010-08-01 13:39:47Z alex $
 * @author  Alessandro Polo
 * @date    Released on 2009-10-19
 ****************************************************************************/
/* Copyright (c) 2007-2010, WOSH - Wide Open Smart Home 
 * by Alessandro Polo - OpenSmartHome.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSmartHome.com WOSH nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY Alessandro Polo ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Alessandro Polo BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ****************************************************************************/

#ifndef __WOSH_DEVICES_PlayerGStreamer010_H__
 #define __WOSH_DEVICES_PlayerGStreamer010_H__

 #include <woshDefs.h>
 #include <map>
 #include <framework/entertainment/MediaList.h>
 #include "PlayerGStreamer.h"
 #include <gst/gst.h>


using namespace wosh;
using namespace wosh::entertainment;


class PlayerGStreamer010 : public PlayerGStreamer
 {
	public:
		/**
		 * @brief   Default constructor. Init vars and GLib main gst_loop, associating it to current instance (this).
		 * @param bundle [in] the parent bundle, see BundleGenericWorker interface
		 * @see     PlayerGStreamer010::instances
		 */
		PlayerGStreamer010( BundleGeneric& bundle );
		/**
		 * @brief   Deconstructor. If playing or idle (thread is stll running), it will be stopped.
		 */
		virtual ~PlayerGStreamer010();


	public:
		virtual WRESULT play( unsigned int index );

		virtual WRESULT play()				{ return play(""); }


		/**
		 * @brief   Play a resource
		 * @param stream_uri [in] the URI of the resource to be played. Multiple protocols are supported:
		 *                         - filesystem [file:///path/to/somefile.avi] (default: '/path/to/somefile.avi' will work too) 
		 *                           Also folders are supported, but it will clear the playlist and enqueue files, not recursive.
		 *                         - Network stream, HTTP [http://www.alessandropolo.name/music/sounday/Longe-at-the-Counter.mp3]
		 *                         - Compact Disc Digital Audio [cdda://4]
		 *                         - DVD [dvd://1]
		 */
		virtual WRESULT play( const std::string& stream_uri );

		virtual WRESULT enqueue( const std::string& stream_uri );

		virtual WRESULT remove( unsigned int index );

		virtual WRESULT pause();
		virtual WRESULT stop();

		virtual WRESULT first();
		virtual WRESULT next();
		virtual WRESULT prev();
		virtual WRESULT last();

		virtual WRESULT clear();

		virtual WRESULT setVolume( int newVolume );
		virtual WRESULT setVolumeOffset( int volume_span );

		virtual WRESULT setMute( bool on );

		virtual void setRepeatItem( bool value );
		virtual void setRepeatPlayList( bool value );

		virtual WRESULT setDeviceDriver( const std::string& dev_driver );
		virtual WRESULT setDeviceOutput( const std::string& dev_file );

		virtual WRESULT setPosition( float position_rate );
		virtual WRESULT setPositionOffset( float position_rate_offset );

		virtual WRESULT setPositionMs( unsigned long position_rate );

		virtual float getPosition();
		virtual std::string getPositionStr();
		virtual unsigned long getPositionMs();

		virtual std::string getDeviceDriver() const		{ return this->device_sink; }
		virtual std::string getDeviceOutput() const		{ return this->device_output; }

		virtual int getVolume();
		virtual bool isMuted();

		virtual bool isPlaying();


		virtual int getPlayListIndex() const		{ return this->playlist.getCurrentIndex(); }

		virtual const wosh::entertainment::MediaList& getPlayList() const { return this->playlist; }
		virtual wosh::entertainment::MediaList& getPlayList()			{ return this->playlist; }

		virtual WRESULT getAPIInfo( std::map<std::string, std::string>& fields );



/** @name GStreamer callbacks
 * @{
 ******************************************************************************/
	protected:

		/**
		 * @brief   GST callback, raised while buffering media
		 * @param [in] percent the relative buffered lenght
		 */
		virtual void item_Buffering( int percent );

		virtual void item_Duration( int64 nanoseconds );

		/**
		 * @brief   GST callback, raised while media has finished
		 */
		virtual void item_EndOfStream();
		/**
		 * @brief   GST callback, raised when some media information (tags) are available
		 * @param [in] fields the available information
		 */
		virtual void item_InfoTag( const std::map<std::string, std::string>& fields );

		/**
		 * @brief   GST callback, raised while GST status changed
		 * @param [in] new_state the new GST state
		 * @param [in] old_state the previous GST state
		 */
		virtual void gst_StateChanged( GstState new_state, GstState old_state );
		/**
		 * @brief   GST callback, raised while GST raised a CRITICAL error
		 * @param [in] message error description
		 */
		virtual void gst_Error( const char* message );
		/**
		 * @brief   GST callback, raised while GST raised a warning error
		 * @param [in] message warning description
		 */
		virtual void gst_Warning( const char* message );
		/**
		 * @brief   GST callback, raised while GST raised an information message
		 * @param [in] message information description
		 */
		virtual void gst_Info( const char* message );

		/**
		 * @brief   GST bus monitor, it will raise the previously defined callbacks
		 */
		friend gboolean bus_call (GstBus *bus, GstMessage *msg, gpointer data);

//@}
/** @name Thread methods
 * @{
 ******************************************************************************/
	protected:
		bool initializingThread();
		void runThread();
		void exitingThread();

		/**
		 * @brief   Overloaded method, it will exit GST loop and stop the thread.
		 */
		WRESULT quitThread( unsigned long timeout = LIMIT_ULONG_MAX );

//@}
/** @name Static methods
 * @{
 ******************************************************************************/
	public:
		/**
		 * @brief   Get GstState as a literal string
		 * @param [in] state the state to be 'translated'
		 * @return  string representation of given state, possible values are {NULL,READY,PAUSED,PLAYING,UNKNOWN}
		 */
		static const char* getGstState2String( GstState state );

		/**
		 * @brief   Wait till GstState is applied, untill timeout.
		 * @param [in] gst_state the state (reference) to be monitored
		 * @param [in] waiting_gst_state the final state to be waited for
		 * @param [in] timeout_ms max time to wait in milliseconds. Check step is 50 milliseconds
		 * @return  true when state is validated, otherwise false.
		 */
		static bool waitGstState( const GstState* gst_state, GstState waiting_gst_state, unsigned long timeout_ms );

//@}
/** @name Internal methods
 * @{
 ******************************************************************************/
	protected:

		WRESULT play_( wosh::entertainment::MediaTrack* item, bool synch = true );

		WRESULT play_index_( unsigned int index, bool synch = true, bool resume_next = false );

		int enqueue_( const std::string& file_url );

		bool isValidFile( const std::string& url_resolved ) const;

		/**
		 * @brief   Change GstState synchronosly, waiting untill timeout.
		 * @param gst_state [in] the state to be applied
		 * @param timeout_ms [in] max time to wait in milliseconds. Check step is 50 milliseconds
		 * @return  true when state is validated, otherwise false.
		 */
		bool gst_change_state_synch( GstState gst_state, unsigned long timeout_ms );

//@}
	private:
		GMainLoop *gst_loop;			///< GLib loop pointer
		GstElement *gst_pipeline;		///< GStreamer pipeline pointer

		GstElement *gst_sink_audio;		///< pointer to the GStreamer Audio Sink
		GstElement *gst_bin_play;		///< pointer to the GStreamer BIN play

		GstState gst_state;				///< (last) gstreamer pipeline state 

		std::string device_sink;		///< output driver GST name (default: alsasink)
		std::string device_output;		///< ALSA device name (default; ..)

		MediaList playlist;				///< the playlist

		short currentRepeat;			///< flag: repeat current item forever
		short playListRepeat;			///< flag: repeat whole playlist forever

		int volume_init;				///< (default) volume value (used only while starting thread)
		int volume_muted;				///< cache of last volume while muted, 0 when not muted

		static std::map<GMainLoop*, PlayerGStreamer010*> instances;	///< global collection of instances
		static MutexRW instancesMux;								///< mutex of global instances-collection


}; // class def


#endif //__WOSH_DEVICES_PlayerGStreamer010_H__
